package com.bolt.support.desensitization.resolver;

import com.bolt.convention.data.DefaultPageInfo;
import com.bolt.convention.data.PageInfo;
import com.bolt.convention.data.ResultMessage;
import com.bolt.support.desensitization.annotation.CascadeSensitive;
import org.springframework.aop.framework.AopInfrastructureBean;

import java.lang.reflect.AnnotatedParameterizedType;
import java.lang.reflect.AnnotatedType;
import java.util.List;

public class ResultMessageTypeResolver implements TypeResolver<ResultMessage<Object>, AnnotatedParameterizedType>, AopInfrastructureBean {

    private final int order = TypeResolvers.randomOrder();

    @Override
    public ResultMessage<Object> resolve(ResultMessage<Object> resultMessage, AnnotatedParameterizedType annotatedParameterizedType) {
        AnnotatedType typeArgument = annotatedParameterizedType.getAnnotatedActualTypeArguments()[0];
        Object data = resultMessage.getData();
        if (data instanceof PageInfo) {
            PageInfo pageInfo = ((PageInfo) data);
            List content = pageInfo.getContent();
            List erased = TypeResolvers.resolve(content, typeArgument);
            return resultMessage.setData(new DefaultPageInfo(pageInfo.getPageNumber(), pageInfo.getPageSize(), erased, pageInfo.getTotalCount()));
        } else {
            Object erased = TypeResolvers.resolve(resultMessage.getData(), typeArgument);
            return resultMessage.setData(erased);
        }

    }

    @Override
    public boolean support(Object value, AnnotatedType annotatedType) {
        return value instanceof ResultMessage && annotatedType instanceof AnnotatedParameterizedType && ((AnnotatedParameterizedType) annotatedType).getAnnotatedActualTypeArguments()[0].isAnnotationPresent(CascadeSensitive.class);
    }

    @Override
    public int order() {
        return order;
    }
}